package com.smy.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.smy.reggie.common.BaseContext;
import com.smy.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter
@Slf4j
public class LoginFilter implements Filter {

    //路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取当前请求路径
        String requestURI = request.getRequestURI();
        log.warn("当前路径被捕捉到了：" + requestURI);

        //设置不需要拦截的路径

        String[] doNotFilter = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/logout",
                "/user/getCode",
                "doc.html",//不知道为何不起作用
                "/webjars/**",
                "swagger-resources",
                "/v2/api-docs"

        };
        //是不是/
        boolean match = PATH_MATCHER.match("/", requestURI);
        if (match)response.sendRedirect("/backend/index.html");

        //2.判断当前路径是否需要拦截
        boolean check = check(doNotFilter, requestURI);

        //3.不需要的直接放行
        if (check){
            log.warn("当前路径不需要拦截");
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断员工当前是否登录
        log.info("判断员工是否登录");
        if(request.getSession().getAttribute("employee") != null){
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            log.info("员工登录");
            return;
        }
        //4.判断用户是否登录
        log.info("判断用户是否登录");
        if(request.getSession().getAttribute("user") != null){
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            log.info("用户是录");
            return;
        }
        //5.未登录
        log.warn("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    //检查路径方法
    public boolean check(String[] doNotFilter,String requestUrl){
        for (String s : doNotFilter) {
            boolean match = PATH_MATCHER.match(s,requestUrl);
            if (match)return true;
        }
        return false;
    }


}
